//
//  YJSenceListCellController.m
//  SnackCourier
//
//  Created by qianfeng01 on 15/7/22.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "YJSenceListController.h"

#import "AFNetworking.h"
#import "YJSalesTopicListdetailsModel.h"
#import "YJSalesTopicListdetailsCell.h"
#import "YJFirstview.h"
#import "UIImageView+WebCache.h"


#import "CreateSales.h"

@interface YJSenceListController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,copy)NSString *imgUrl;

@end

@implementation YJSenceListController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentPage =0;
    [self createNavigationItem];
    self.title =self.sencelmodel.title;
    self.imgUrl =[[NSString alloc] init];
    self.dataArray =[[NSMutableArray alloc] init];
    NSString *urlStr =[NSString stringWithFormat:kWhatbuyUrl,(long)self.sencelmodel.id,self.currentPage];
    [self createHttpRequest];
    [self initUI];
    [self loadData:urlStr];
    [self refreshData];
    
}

-(void)initUI{
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection =UICollectionViewScrollDirectionVertical;
    flowLayout.minimumLineSpacing =10;
    flowLayout.itemSize =CGSizeMake((self.view.frame.size.width-10)/2.0, 260);
    self.automaticallyAdjustsScrollViewInsets =NO;
    self.collectionView =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64-59) collectionViewLayout:flowLayout];
    self.collectionView.delegate =self;
    self.collectionView.dataSource =self;
    self.collectionView.backgroundColor =[UIColor colorWithWhite:0.9 alpha:1];
    [self.collectionView registerNib:[UINib nibWithNibName:@"YJSalesTopicListdetailsCell" bundle:nil] forCellWithReuseIdentifier:@"YJSalesTopicListdetailsCell"];
    [self.collectionView registerClass:[YJFirstview class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YJFirstview"];
    [self.view addSubview:self.collectionView];
    
}

-(void)loadData:(NSString *)urlStr{
    NSString *path =[YJHelper getFullPathWithFile:urlStr];
    BOOL isExist=[[NSFileManager defaultManager] fileExistsAtPath:path];
    BOOL isTimeout=[YJHelper isTimeOutWithFile:urlStr timeOut:24*60*60];
    if ((isExist==YES)&&(isTimeout==NO)) {
        NSData *data =[NSData dataWithContentsOfFile:[YJHelper getFullPathWithFile:urlStr]];
        if (self.currentPage==1) {
            [self.dataArray removeAllObjects];
        }
        
        NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *datadic = dicts[@"data"];
        self.imgUrl =datadic[@"picUrl"];
        NSArray *array =datadic[@"productList"];
        for (NSDictionary *ditc in array) {
            YJSalesTopicListdetailsModel *model =[[YJSalesTopicListdetailsModel alloc] init];
            [model setValuesForKeysWithDictionary:ditc];
            [self.dataArray addObject:model];
        }
        [self.collectionView reloadData];
        [self endRefreshing];
        return;
    }
    
    __weak typeof (self)weakSelf=self;
    [self.manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            
            NSDictionary *data = dicts[@"data"];
            weakSelf.imgUrl =data[@"picUrl"];
            NSArray *array =data[@"productList"];
            for (NSDictionary *ditc in array) {
                YJSalesTopicListdetailsModel *model =[[YJSalesTopicListdetailsModel alloc] init];
                [model setValuesForKeysWithDictionary:ditc];
                [weakSelf.dataArray addObject:model];
            }
            [weakSelf.collectionView reloadData];
        }
        [weakSelf endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}
-(void)refreshData{
    __weak typeof(self) weakSelf=self;//声明若引用
    [self.collectionView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //重新下载数据
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;//标记正在刷新
        weakSelf.currentPage=0;
        [weakSelf.dataArray removeAllObjects];
        NSString *urlStr=[NSString stringWithFormat:kWhatbuyUrl,(long)weakSelf.sencelmodel.id,(long)weakSelf.currentPage];
        [weakSelf loadData:urlStr];
    }];
    
    //下拉加载更多
    [self.collectionView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return ;
        }
        weakSelf.isLoadMore=YES;//标记正在刷新
        weakSelf.currentPage ++;
        NSString *urlStr=[NSString stringWithFormat:kWhatbuyUrl,(long)weakSelf.sencelmodel.id,(long)weakSelf.currentPage];
        [weakSelf loadData:urlStr];
    }];
}

-(void)endRefreshing{
    if (self.isRefreshing) {
        //正在刷新，就结束刷新
        self.isRefreshing=NO;//标记刷新结束
        [self.collectionView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore=NO;
        [self.collectionView footerEndRefreshing];
    }
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YJSalesTopicListdetailsCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"YJSalesTopicListdetailsCell" forIndexPath:indexPath];
    YJSalesTopicListdetailsModel *model =self.dataArray[indexPath.row];
    [cell showDataWithModel:model];
    cell.backgroundColor =[UIColor whiteColor];
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *view =nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        view =[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YJFirstview" forIndexPath:indexPath];
        UIImageView *imgView =[[UIImageView alloc] initWithFrame:view.frame];
        [imgView sd_setImageWithURL:[NSURL URLWithString:self.imgUrl]];
        [view addSubview:imgView];
    }
    return view;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(0, 80);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    YJSalesTopicListdetailsModel *model =self.dataArray[indexPath.row];
    YJImmediatelygrabController *controller =[CreateSales createVC:model.id];
    controller.title =@"商品详情";
    [self.navigationController pushViewController:controller animated:YES];
    
}




@end
